package deviceauthlogic

import (
	"context"
	"gitee.com/unitedrhino/protocol-wumei/service/pwumeisvr/internal/domain"
	"gitee.com/unitedrhino/protocol-wumei/service/pwumeisvr/internal/logic"
	"gitee.com/unitedrhino/protocol-wumei/service/pwumeisvr/internal/svc"
	"gitee.com/unitedrhino/protocol-wumei/service/pwumeisvr/pb/pwumei"
	"gitee.com/unitedrhino/share/ctxs"
	"gitee.com/unitedrhino/share/errors"
	"gitee.com/unitedrhino/things/service/dmsvr/pb/dm"
	"gitee.com/unitedrhino/things/share/devices"
	"github.com/zeromicro/go-zero/core/logx"
)

type LoginAuthLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginAuthLogic {
	ctx = ctxs.WithRoot(ctx)
	return &LoginAuthLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 设备登录认证
func (l *LoginAuthLogic) LoginAuth(in *pwumei.LoginAuthReq) (*pwumei.Response, error) {
	ci, err := domain.ParseClientID(in.ClientID)
	if err != nil {
		return nil, err
	}
	pi, err := logic.GetProductInfo(l.ctx, l.svcCtx, ci.ID)
	if err != nil {
		l.Error(err)
		return nil, err
	}
	userName := pi.ProtocolConf["userName"]
	password := pi.ProtocolConf["password"]
	//mqttSecret := pi.Tags["mqttSecret"]
	if userName != in.Username {
		l.Error(err)
		return nil, errors.Permissions
	}
	switch ci.AuthType {
	case domain.AuthTypeS:
		if password != in.Password {
			l.Error(err)
			return nil, errors.Permissions
		}
	case domain.AuthTypeE:
		//todo
		l.Error(err)
		return nil, errors.Permissions
	}
	di, err := l.svcCtx.Protocol.DeviceCache.GetData(l.ctx, devices.Core{
		ProductID:  pi.ProductID,
		DeviceName: ci.DeviceName,
	})
	if err != nil || di != nil && di.ProductID != pi.ProductID {
		if errors.Cmp(err, errors.NotFind) || di != nil && di.ProductID != pi.ProductID {
			_, err := l.svcCtx.Protocol.DeviceM.DeviceInfoCreate(l.ctx, &dm.DeviceInfo{
				ProductID:  pi.ProductID,
				DeviceName: ci.DeviceName,
			})
			if err != nil {
				l.Error(err)
			}
			return &pwumei.Response{}, err
		}
		l.Error(err)
		return nil, err
	}

	return &pwumei.Response{}, nil
}
